package de.tum.in.eist.poll.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;

import de.tum.in.eist.poll.shared.Student;
import de.tum.in.eist.poll.shared.User;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class EIST_POLL implements EntryPoint {

	/**
	 * This is the entry point method.
	 */
	public final void onModuleLoad() {
		showLogin();
	}

	/**
	 * Show the login window.
	 */
	private void showLogin() {
		Startpage page = new Startpage();
		page.setOnSuccessfulLoginHandler(handler);
		page.loadWebsite();
	}

	private boolean logoutButtonVisible = false;

	/**
	 * Handles the onLogin event.
	 */
	private OnSuccessfulLoginHandler handler = new OnSuccessfulLoginHandler() {

		@Override
		public void successfulLogin(final User user) {
			final Button logout = new Button("Logout");
			logout.addClickHandler(new ClickHandler() {

				@Override
				public void onClick(final ClickEvent event) {
					Webpage.getService().logout(new AsyncCallback<Void>() {

						@Override
						public void onSuccess(final Void result) {
							RootPanel.get("logout").clear();
							showLogin();
						}

						@Override
						public void onFailure(final Throwable caught) {
							// TODO Auto-generated method stub

						}
					});
				}
			});
			RootPanel.get("logout").clear();
			RootPanel.get("logout").add(logout);

			if (user instanceof Student) {
				// Show the poll page to a student
				final SelectLecture lecture = new SelectLecture();
				lecture.setOnSelectLectureHandler(selectHandler);
				lecture.loadWebsite();
			} else {
				// Show the statistics to a lecturer
				final Statistics statistics = new Statistics();
				statistics.loadWebsite();
			}
		}
	};

	/**
	 * Handles the onSelectLecture event.
	 */
	private OnSelectLectureHandler selectHandler = new OnSelectLectureHandler() {

		@Override
		public void selectLecture(final String lectureID) {
			final Poll poll = new Poll(lectureID);
			poll.loadWebsite();
		}
	};
}
